<template>
  <div class="rent-application">
    <el-card class="application-card">
      <template #header>
        <div class="card-header">
          <span>租房申请</span>
        </div>
      </template>

      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <!-- 房屋信息展示 -->
        <div class="house-info" v-if="house && house.house_id">
          <h3>{{ house.description }}</h3>
          <p class="address">{{ house.district }} - {{ house.address }}</p>~
          <p class="price">月租金：¥{{ house.monthly_rent }}/月</p>
        </div>
        <div v-else class="loading-info">
          <el-empty description="正在加载房屋信息..." />
        </div>

        <!-- 租期选择 -->
        <el-form-item label="租期" prop="dateRange" required>
          <el-date-picker
            v-model="formData.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabledDate="disabledDate"
          />
        </el-form-item>

        <!-- 租金计算 -->
        <div class="rent-calculation" v-if="house && house.monthly_rent">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="租期时长">
              {{ rentDuration }} 个月
            </el-descriptions-item>
            <el-descriptions-item label="月租金">
              ¥{{ house.monthly_rent }}
            </el-descriptions-item>
            <el-descriptions-item label="总租金">
              <span class="total-amount">¥{{ totalAmount }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 支付方式选择 -->
        <el-form-item label="支付方式" prop="paymentMethod" required>
          <el-radio-group v-model="formData.paymentMethod">
            <el-radio value="微信支付">
              <el-icon><WalletFilled /></el-icon> 微信支付
            </el-radio>
            <el-radio value="支付宝">
              <el-icon><Money /></el-icon> 支付宝
            </el-radio>
            <el-radio value="银行转账">
              <el-icon><CreditCard /></el-icon> 银行转账
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 提交按钮 -->
        <div class="submit-section">
          <el-button type="primary" :loading="loading" @click="submitApplication">
            提交申请
          </el-button>
          <el-button @click="$router.back()">返回(Esc)</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { WalletFilled, Money, CreditCard } from '@element-plus/icons-vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 房屋信息
const house = ref({})

// 表单数据
const formData = ref({
  dateRange: null,
  paymentMethod: ''
})

// 表单验证规则
const rules = {
  dateRange: [
    { required: true, message: '请选择租期', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 禁用的日期（今天之前的日期不可选）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 86400000
}

// 计算租期时长（月）
const rentDuration = computed(() => {
  if (!formData.value.dateRange) return 0
  const [start, end] = formData.value.dateRange
  if (!start || !end) return 0
  const months = (end.getFullYear() - start.getFullYear()) * 12 + 
                (end.getMonth() - start.getMonth())
  return months + 1 // 包含起始月
})

// 计算总租金
const totalAmount = computed(() => {
  if (!house.value || !house.value.monthly_rent || !rentDuration.value) {
    return '0.00'
  }
  return (rentDuration.value * house.value.monthly_rent).toFixed(2)
})

// 获取房屋信息
const fetchHouseInfo = async () => {
  try {
    const response = await axios.get(`http://127.0.0.1:5000/api/houses/getHouseDetails/${route.params.houseid}`)
    console.log('API Response:', response.data)
    
    if (response.data) {
      house.value = response.data
      console.log('Processed house data:', house.value)
    } else {
      console.error('Invalid API response:', response.data)
      ElMessage.error('获取房屋信息失败：数据为空')
    }
  } catch (error) {
    console.error('获取房屋信息失败:', error)
    ElMessage.error('获取房屋信息失败，请稍后重试')
  }
}

// 提交租房申请
const submitApplication = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    const [startDate, endDate] = formData.value.dateRange
    
    const response = await axios.post('http://127.0.0.1:5000/api/rent/apply', {
      house_id: parseInt(route.params.houseid),
      landlord_id: house.value.landlord_id,
      start_date: startDate.toISOString().split('T')[0],
      end_date: endDate.toISOString().split('T')[0],
      amount: parseFloat(totalAmount.value),
      pay_type: formData.value.paymentMethod
    }, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })
    console.log('API Response:', response.data)
    if (response.data.status === 200) {
      ElMessage.success('申请提交成功')
      const result = response.data.data
      // 跳转合同页，传参数
      router.push({
        path: '/contract',
        query: {
          contractId: 'ZF0000' + result.rent_id, 
          tenantName: result.tenant_name,                 
          landlordName: result.landlord_name,
          houseName: result.house_name,
          startDate: result.start_date,
          endDate: result.end_date,
          rentDate: result.rent_date,
          amount : result.amount,
          payType : result.pay_type
        }
      })
    } else {
      ElMessage.error(response.data.msg || '申请提交失败')
    }
  } catch (error) {
    console.error('提交申请失败:', error)
    ElMessage.error(error.response?.data?.msg || '提交申请失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 全局键盘事件处理函数
const handleKeydown = (e) => {
  // 处理Esc快捷键
  if (e.key === 'Escape') {
    e.preventDefault() // 阻止默认行为
    router.back()
  }
}

onMounted(async () => {
  console.log('Component mounted, houseid:', route.params.houseid)
  await fetchHouseInfo()
  
  // 添加全局键盘事件监听
  window.addEventListener('keydown', handleKeydown)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  // 移除全局键盘事件监听
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.rent-application {
  max-width: 720px;
  margin: 30px auto;
  padding: 0 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #2c3e50;
}

.application-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.08);
  padding: 24px;
  background: #fff;
  transition: box-shadow 0.3s ease;
}

.application-card:hover {
  box-shadow: 0 12px 28px rgba(0,0,0,0.12);
}

.card-header {
  font-size: 26px;
  font-weight: 700;
  color: #34495e;
  margin-bottom: 28px;
  user-select: none;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.house-info {
  margin-bottom: 36px;
  padding: 24px;
  background: linear-gradient(135deg, #e3f2fd, #f9fbff);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transition: background 0.4s ease;
}

.house-info h3 {
  margin: 0 0 12px 0;
  font-size: 22px;
  font-weight: 600;
  color: #1f2d3d;
}

.house-info .address {
  color: #5a6a81;
  font-size: 15px;
  margin-bottom: 8px;
  letter-spacing: 0.3px;
}

.house-info .price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: 700;
  margin-top: 4px;
}

.loading-info {
  margin: 30px 0;
  text-align: center;
  font-size: 16px;
  color: #909399;
}

.rent-calculation {
  margin: 28px 0;
}

.el-descriptions__label {
  font-weight: 600;
  color: #606266;
  font-size: 15px;
}

.el-descriptions__content {
  font-size: 17px;
  font-weight: 600;
  color: #303133;
}

.total-amount {
  color: #f56c6c;
  font-size: 24px;
  font-weight: 700;
}

.el-form-item {
  margin-bottom: 30px;
}

.el-date-picker {
  width: 100%;
  border-radius: 8px;
  font-size: 15px;
}

.el-radio-group {
  display: flex;
  gap: 24px;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.el-radio {
  display: flex;
  align-items: center;
  height: 40px;
  cursor: pointer;
  padding: 6px 14px;
  border-radius: 8px;
  transition: background-color 0.2s ease;
  user-select: none;
}

.el-radio:hover {
  background-color: #f0f6ff;
}

.el-radio.is-checked {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.el-radio .el-icon {
  margin-right: 8px;
  font-size: 22px;
  color: #409eff;
}

.submit-section {
  margin-top: 38px;
  text-align: center;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.el-button {
  min-width: 130px;
  font-weight: 600;
  border-radius: 8px;
  font-size: 16px;
  padding: 10px 0;
  transition: background-color 0.3s ease;
}

.el-button:hover {
  filter: brightness(1.1);
}

.el-button[type='primary'] {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button[type='primary']:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>
